package com.alander.nexusgo.im.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * Token服务类
 */
@Service
public class TokenService {

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    private static final String TOKEN_PREFIX = "nexusgo:im:login:token:";

    /**
     * 创建IM登录token
     *
     * @param userId 用户ID
     * @param appId  应用ID
     * @return token
     */
    public String createImLoginToken(long userId, int appId) {
        String token = UUID.randomUUID() + "%" + appId;
        redisTemplate.opsForValue().set(TOKEN_PREFIX + token, userId, 5, TimeUnit.MINUTES);
        return token;
    }

    /**
     * 根据token获取用户ID
     *
     * @param token token
     * @return 用户ID
     */
    public Long getUserIdByToken(String token) {
        Object userId = redisTemplate.opsForValue().get(TOKEN_PREFIX + token);
        return userId == null ? null : Long.valueOf(userId.toString());
    }
}